package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type MaterialThemeTerminals struct{}

func (MaterialThemeTerminals) Create(ctx context.Context, db *gorm.DB, themeID, robotID, terminalType string, upgradeStatus,
	upgradeType int) (err error) {
	m := dal.Use(db).MaterialThemeTerminals
	var d models.MaterialThemeTerminals
	d.ID, _ = helper.UUID{}.String()
	d.ThemeID = themeID
	d.RobotID = robotID
	d.TerminalType = terminalType
	d.UpgradeStatus = upgradeStatus
	d.UpgradeType = upgradeType
	d.CreatedAt = time.Now().Unix()
	m.WithContext(ctx).Create(&d)
	return nil
}

func (MaterialThemeTerminals) PreDelete(ctx context.Context, db *gorm.DB, themeID, robotID string) (err error) {
	// 没有时不删除!!!
	if robotID == "" || themeID == "" {
		return
	}
	m := dal.Use(db).MaterialThemeTerminals
	tx := m.WithContext(ctx)
	if themeID != "" {
		tx = tx.Where(m.ThemeID.Eq(themeID))
	}
	if robotID != "" {
		if strings.Contains(robotID, ",") {
			tx = tx.Where(m.RobotID.In(strings.Split(robotID, ",")...))
		} else {
			tx = tx.Where(m.RobotID.Eq(robotID))
		}
	}
	tx.Updates(&models.MaterialThemeTerminals{
		UpgradeStatus: 0,
		UpgradeType:   3, // 删除
	})
	return
}
